package com.atguigu.gmall.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lfy
 * @Description
 * @create 2023-08-05 10:33
 */
@Service
public class AliPayService implements PayService {


    @Autowired
    AlipayClient alipayClient;

    @Autowired
    AlipayProperties alipayProperties;


    @Autowired
    OrderFeignClient orderFeignClient;

    @Override
    public String generatePayPage(Long orderId) throws AlipayApiException {
        //1、创建一个 AlipayClient

        //2、设置支付请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //一旦支付成功以后，浏览器要跳到哪里，在这里设置好。
        //支付成功以后，支付宝给浏览器响应时就会告诉浏览器重定向到 Return_url 指定的位置
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());


        //3、远程获取订单数据
        OrderInfo orderInfo = orderFeignClient.getOrderInfoById(orderId).getData();

        //
        Date expireTime = orderInfo.getExpireTime();
        String date = DateUtil.formatDate(expireTime, "yyyy-MM-dd HH:mm:ss");
        //商户订单号，商户网站订单系统中唯一订单号，必填
        //付款金额，必填
        //订单名称，必填
        //商品描述，可空

        Map<String,Object> bizContent = new HashMap<>();

        bizContent.put("out_trade_no",orderInfo.getOutTradeNo());
        bizContent.put("total_amount",orderInfo.getTotalAmount().toString());
        bizContent.put("subject","尚品汇-订单【"+orderInfo.getOutTradeNo()+"】");
        bizContent.put("body",orderInfo.getTradeBody());
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
        bizContent.put("time_expire",date);
        //所有可以传的参数参考：https://opendocs.alipay.com/open/59da99d0_alipay.trade.page.pay?pathHash=8e24911d&ref=api&scene=22



        //把所有数据准备成一个json放到 BizContent
        alipayRequest.setBizContent(JSONs.obj2JsonStr(bizContent));


        //执行支付请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
}
